package mrusanov.league

class LeagueInfoSystem(leagueInfoList:Seq[LeagueInfo]) {
  val levels = leagueInfoList.map(_.level).max + 1
  val topLeague = leagues(0)
  def leagues(level:Int) = leagueInfoList.filter(_.level == level)(0)

  validateLeagueSystem()
  private def validateLeagueSystem() {
    require(leagueInfoList.groupBy(_.level).size == leagueInfoList.size, "duplicate leagues")
    require(topLeague.leagues == 1, "Top league info must have 1 league")
    require(leagueInfoList.map(_.level).toSet == 0.until(levels).toSet, "Not all league infos are present")
    leagueInfoList foreach( info => {
      val lvl = info.level
      require(info.promoted <= info.teams, "Too many promoted teams in league " + info.level)

      if (lvl == 0) {
        if (levels != 1) {
          val lower = leagues(lvl + 1)
          require(lower.leagues * lower.promoted <= info.teams)
        }
      } else if (lvl != levels - 1) {
          val lower = leagues(lvl + 1)
          require(info.teams * info.leagues >= lower.promoted * lower.leagues + info.promoted * info.leagues, "Too many promoted teams")
          require((lower.promoted * lower.leagues) % info.leagues == 0, "Not able to distribute promoted teams between leagues")
      }
    })
  }
}
